import { ChangeDetectorRef, Component, OnDestroy, OnInit, Renderer2, ViewRef } from '@angular/core';
import { Subscription } from 'rxjs';
import { concatMap } from 'rxjs/operators';
import { of } from 'rxjs/internal/observable/of';
import { ApesMessageService } from '@shared/apes/message';
import { WebsocketService } from '@core/services/websocket/websocket.service';
import { ApiService } from '@core/services/http/api.service';
import { NotificationsService } from '@core/services/notification/notification.service';
import { FormService } from '@core/services/form.service';
import { dateFormat, deepClone, getValueUsingField } from '../../../utils/utils';
import { ToDoItem } from '@shared/todo';
import { UserAuthService } from '@core/services/user-auth.service';
import { XlsxService } from '@shared/apes/xlsx';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import { Router } from '@angular/router';
import { ApesDrawerCustomGridComponent } from '@shared/ag-grid-ext/drawer-custom/drawer-custom-grid.component';
import { ApesDrawerService } from '@shared/apes/drawer';
import { Events } from '@core/services/events/Events';
import { ApesDialogComponent } from '@shared/dialog';
import { ApesModalService } from '@shared/apes/modal';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { ButtonService } from '@core/services/button.service';

@Component({
  selector: 'home-page-fn',
  templateUrl: './home-page-fn.component.html',
  styleUrls: ['./home-page-fn.component.scss'],
})
export class HomePageFnComponent implements OnInit, OnDestroy {

  todoTitle: any = '待办';

  messagesSubscription: Subscription;
  data: ToDoItem[] = [];        // 请求数据
  todoData: any[] = [];         // 请求数据
  initialData: any[] = [];      // 原始数据
  initialTodoData: any[] = [];  // 原始数据
  showData: any [] = [];        // 过滤显示数据
  showDataLoading: boolean = false;
  showAllItemType: boolean = true;
  indeterminate: boolean = false;
  showItemType: any[] = [];
  showMore: boolean = false;
  searchValue: any;
  processType: any = { name: '全部', type: 0 };
  sortType: any = { name: '按推送时间排序', type: 0 };
  count = 0;
  time: any;
  userId: any = '';

  deptId: any;
  userInfo: any = {};

  fnWorkbench: boolean = false;
  fnWorkbenchMenu: any[] = [];
  fnWorkbenchPlanState: any[] = [];
  fnWorkbenchMessage: any = 'endItem';
  endItem: any[] = [];
  messageItem: any[] = [];
  endItemIsLoading: boolean = false;
  messageItemIsLoading: boolean = false;

  refreshFnWorkbench: any;
  assistantInitItems: any[] = [];

  assistantItems: any[] = [];

  searchReceiptValue: any = null;
  popoverItem: any[] = [];

  storeData: any = {};
  personalData: any = {};
  intelligentData: any = [];
  intelligentLoading: boolean = false;


  constructor(
    private msg: ApesMessageService,
    private ws: WebsocketService,
    private apiService: ApiService,
    private ns: NotificationsService,
    private formService: FormService,
    private userService: UserAuthService,
    protected cd: ChangeDetectorRef,
    private  xlsx: XlsxService,
    protected rs: ReuseTabService,
    private router: Router,
    protected drawerService: ApesDrawerService,
    protected contextService: ApesContextMenuService,
    protected events: Events,
    private renderer: Renderer2,
    private buttonService: ButtonService,
  ) {
  }

  ngOnInit() {
    this.initData();
  }

  initData() {

    this.userId = this.userService.getUserInfoObj().userAccount.id;

    this.backlogSubscription();

    // this.fullData();
    if (this.time) {
      clearInterval(this.time);
    }
    setTimeout(() => {
      this.time = setInterval(() => {
        if (!(<ViewRef>this.cd).destroyed) {
          this.cd.detectChanges();
        }
      }, 10000);
    }, 1000);

    let platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : '';

    if (platform == 'fn') {
      this.fnWorkbench = true;
      // this.events.subscribe('checkFnWorkbench', data => {
      //   this.refreshHomeData();
      // });

      this.refreshHomeData();
    }

  }

  backlogSubscription() {
    this.messagesSubscription = this.ws.messagesObserver
      .pipe(
        concatMap(data => {
          return of(data);
        })).subscribe(
        (item) => {
          const data = JSON.parse(item);
          if (data.topic === 'ws.wf.count') {
            if (data.action === 'executePreTask') {
              this.audio();
              const title = data.task.processDefinitionName + ':' + data.task.taskName;
              this.ns.generate({
                title: title,
                body: '您有新待办，请及时处理！',
                data: data,
                icon: 'assets/tmp/img/oa/todolist.png',
              })
                .subscribe((value) => {
                  this.formService.navigateToForm(value.notification.data.task);
                });
            } else {
              const title = data.task.processDefinitionName + ':' + data.task.taskName;
              this.ns.generate({
                title: title,
                body: '待办已处理！',
                data: data,
                icon: 'assets/tmp/img/oa/finish.png',
              }).subscribe();
            }
            this.dealData(data.task, data.action);
          } else if (data.topic == 'ws.todo') {
            const title = data.message.businessTypeName + ':' + data.message.description;
            let body;
            let icon;
            let source;
            if (data.action === 'createTask') {
              body = '您有新待办，请及时处理！';
              icon = 'assets/tmp/img/oa/todolist.png';
              this.audio();
            } else if (data.action === 'updateTask') {
              body = '您有待办更新，请及时处理！';
              icon = 'assets/tmp/img/oa/todolist.png';
            } else if (data.action === 'finishTask') {
              body = '待办已处理！';
              icon = 'assets/tmp/img/oa/finish.png';
            }
            source = {
              title: title,
              body: body,
              icon: icon,
            };
            this.ns.generate(source)
              .subscribe((value) => {
                // console.log('---------------------------');
                if (data.action == 'createTask' || data.action == 'updateTask') {
                  this.formService.navigateToForm(value.notification.data.message);
                }
              });
            // console.log('增量todo', data);
            this.dealTodoData(data.message, data.action);
          } else if (data.topic == 'ws.onOpen') {
            this.fullData();
          }
        },
      );

    // this.fullData();
  }

  refreshHomeData() {
    this.checkFnWorkbench();
    this.checkDeptId();
    this.getStoreData();
    this.getPersonalData();
    this.getIntelligentAssistant();
  }

  checkFnWorkbench() {
    let api = 'fn.workDeskConfig.workDeskMenuEntrance';
    this.apiService.post(api, {}).subscribe((data) => {
      // console.log(data);
      if (data) {
        this.fnWorkbenchMenu = data;
      }
    });

    if (this.refreshFnWorkbench) {
      clearInterval(this.refreshFnWorkbench);
    }
    this.refreshFnWorkbench = setInterval(() => {
      this.refreshHomeData();
    }, 600000);

  }

  fnWorkbenchImg(param) {
    return param.pic;
  }

  openContextLink(menu) {
    let api = menu.menuId;
    if (api == null) {
      this.msg.error('该链接尚未存在，麻烦核实！', { 'apesDuration': 5000 });
      return false;
    }

    if (menu.hasOwnProperty('count_api')) {
      this.apiService.post(menu.count_api, { id: menu.id }).subscribe(() => {
      });
    }

    const formId = api;
    const url = '/' + formId;
    if (menu.name == '收款') {
      let href = window.location.href.split('#');
      let h = href[0].split('erp');
      window.open(h[0] + formId, '_blank');
    } else {
      if (this.rs.exists(url) || this.rs.curUrl === url) {
        this.router.navigateByUrl(formId).then();
      } else {
        this.router.navigate([formId]).then();
      }
    }
  }

  openContextDrawer(state) {
    let drawer;
    let formId = state.formId ? state.formId : state.FORM_ID ? state.FORM_ID : '';
    let api = state.api ? state.api : state.API ? state.API : '';
    let name = state.name ? state.name : state.detailName;

    if (state.hasOwnProperty('count_api')) {
      this.apiService.post(state.count_api, { id: state.id }).subscribe(() => {
      });
    }

    let openDrawer = drawer ? drawer : ApesDrawerCustomGridComponent;

    let drawerRef = this.drawerService.create<ApesDrawerCustomGridComponent, { formId: string, api: string, data: any }, string>({
      apesTitle: name,
      apesContent: openDrawer,
      apesWidth: '60vw',
      apesContentParams: {
        formId: formId,
        api: api,
        data: state,
      },
    });

    drawerRef.afterOpen.subscribe(data => {
    });

    drawerRef.afterClose.subscribe(data => {
    });
  }

  openAssistantLink(params) {
    let resultData = params['condition'];
    let formId = params.formId;
    let config = { 'OAInterface': false, 'api': 'pub.query' };
    this.contextService.openContextLink(resultData, formId, config);
  }

  checkPersonalData() {
    // console.log('--');

    if (!this.userInfo) return;
    let deptName = this.userInfo.post.dept ? this.userInfo.post.dept.name : null;
    let userName = this.userInfo.name;
    let userId = this.userInfo.userId;
    let nowDate = [new Date(), new Date()];
    let param = {
      action: 'link',
      formId: 'report/cz.employeeYYCZTJ.query',
      condition: {
        DEPT_ID: this.deptId,
        DEPT_ID_name: deptName,
        PARTY_ROLE_ID: userId,
        PARTY_ROLE_ID_name: userName,
        TJRQ: nowDate,
        api: 'pub.query',
        formId: 'report/fn.innerPickDeliveryUpCar.query',
        OAInterface: false,
      },
    };
    this.checkAssistant(param);
  }

  checkAssistant(param) {
    // console.log(param);
    if (param.hasOwnProperty('msg')) {
      this.msg.error(param.msg);
      return;
    }
    let action = param.action;
    if (action == 'link') {
      this.openAssistantLink(param);
    } else if (action == 'drawer') {
      this.openContextDrawer(param);
    }
  }

  fullData() {

    let data = { 'page': 0, 'size': 50 };
    this.fullDataPost(data, []);

    let todo = { 'userId': this.userId };
    this.apiService.post('todo.todoList', todo).subscribe((items) => {
      this.todoData = items;
      // console.log('全量todo--', items);
      this.refactorTodoData();
    });
  }

  fullDataPost(setData, resData) {
    this.showDataLoading = true;
    this.apiService.post('wf.getTasks', setData).subscribe((items) => {
      resData = [...resData, ...items];
      if (items.length == setData['size']) {
        setData['page'] = setData['page'] + 1;
        this.fullDataPost(setData, resData);
      } else if (items.length < setData['size']) {
        this.data = this.finishingData(resData);
        this.refactorData();
      }
    });
  }

  finishingData(resData) {
    let data = [];
    let item = [];
    resData.forEach((res) => {
      let resPName = res.processDefinitionName;
      let check = true;
      let index = 0;
      item.forEach((i, n) => {
        if (i == resPName) {
          index = n;
          check = false;
        }
      });
      if (check) {
        item.push(resPName);
        data.push({ title: resPName, list: [...res] });
      } else {
        data[index].list.push(res);
      }
    });
    return data;
  }


  dealData(task: any, action: string) {
    let bPush = true;
    this.data.forEach((x, xIndex) => {
      if (x.title === task.processDefinitionName) {
        if (action === 'executePreTask') {
          this.data[xIndex].list.push(task);
        } else {
          let i = xIndex;
          this.data[i].list.forEach((item, index) => {
            if (item.taskId == task.taskId) {
              this.data[i].list.splice(index, 1);
            }
          });
        }
        bPush = false;
        return false;
      }
    });
    if (bPush === true && action === 'executePreTask') {
      this.data.push({ title: task.processDefinitionName, list: [task] });
    }
    this.data = [...this.data];
    this.refactorData();
  }

  dealTodoData(task: any, action: string) {
    if (action === 'createTask') {
      this.todoData.push(task);
    } else {
      this.todoData.forEach((x, index) => {
        if (x.taskId === task.taskId) {
          if (action === 'updateTask') {
            this.todoData[index] = task;
          } else if (action === 'finishTask') {
            this.todoData.splice(index, 1);
          }
        }
      });
    }

    this.todoData = [...this.todoData];
    this.refactorTodoData();
  }

  getCount() {
    let count = 0;
    if (!this.data) this.data = [];
    if (!this.todoData) this.todoData = [];
    let _data = deepClone(this.data);
    _data.forEach((value) => {
      if (value.list instanceof Array) {
        count = count + value.list.length;
      } else {
        count = count + 1;
      }
    });
    let _todoData = deepClone(this.todoData);
    _todoData.forEach((value) => {
      count = count + 1;
    });
    return count;
  }

  refactorData() {
    // console.log('待办原始数据--', this.data);
    this.initialData = [];
    let refactorData = deepClone(this.data);
    let showData = [];
    refactorData.forEach((items) => {
      if (items.hasOwnProperty('list')) {
        items.list.forEach((item) => {
          item['itemType'] = item['processDefinitionName'];
          item['todoNode'] = item['taskName'];
          item['processType'] = '经';
          // item['expiredTime'] = new Date('2020/12/22 16:24:00').getTime();
          item['expiredTime'] = 0;
          item = this.filterContent(item);
          showData.push(item);
          this.refactorItemType(item);
        });
      }
    });
    this.initialData = [...showData];
    this.showToDoListData();
  }

  refactorTodoData() {
    // console.log(this.todoData);
    this.initialTodoData = [];
    let refactorTodoData = deepClone(this.todoData);
    let showData = [];
    refactorTodoData.forEach((item) => {
      item['itemType'] = item['businessTypeName'];
      item['todoNode'] = item['description'];
      if (item['tags'] == '经办') {
        item['processType'] = '经';
      } else {
        item['processType'] = '督';
      }
      if (item['formId'] && item['formId'].indexOf('/') == 0) {
        item['formId'] = item['formId'].slice(1);
      }
      item['expiredTime'] = item['expired'] ? item['expired'] : 0;
      item = this.filterContent(item);
      showData.push(item);
      this.refactorItemType(item);
    });
    this.initialTodoData = [...showData];
    this.showToDoListData();
  }

  filterContent(item) {
    if (item.hasOwnProperty('content')) {
      item['carLicense'] = item.content['车牌'];
      item['contentData'] = [];
      for (let key in item.content) {
        if (key != '车牌' && item.content[key] != '' && item.content[key] != undefined) {
          item['contentData'].push(key + ':' + item.content[key]);
        }
      }
    }
    return item;
  }

  refactorItemType(item) {
    let check = true;
    this.showItemType.forEach((type) => {
      if (type.name == item.itemType) {
        check = false;
      }
    });
    if (check) {
      let type = { name: item.itemType, value: item.itemType, checked: true };
      this.showItemType.push(type);
    }
  }

  showToDoListData() {
    this.count = this.getCount();
    this.searchValue = null;
    let showData = [...this.initialData, ...this.initialTodoData];
    this.sortShowData(showData);
  }

  showFilterToDoListData(keyword) {
    let filterData = this.initialData.filter(item => {
      return this.filter(item, keyword);
    });
    let filterTodoData = this.initialTodoData.filter(item => {
      return this.filter(item, keyword);
    });
    let showData = [...filterData, ...filterTodoData];
    this.sortShowData(showData);
  }

  changeSort() {

    if (this.searchValue) {
      this.showFilterToDoListData(this.searchValue);
    } else {
      let showData = [...this.initialData, ...this.initialTodoData];
      this.sortShowData(showData);
    }
  }

  sortShowData(data: any[]) {

    let process = this.processType['type'];
    let sort = this.sortType['type'];

    let filterData = [];

    if (this.showItemType.length > 0) {
      this.showItemType.forEach((type) => {
        if (type.checked) {
          data.filter((item) => {
            if (item.itemType == type.value) {
              filterData.push(item);
            }
          });
        }
      });
    } else {
      filterData = [...data];
    }

    switch (process) {
      case 1:
        filterData = filterData.filter((item) => {
          return item.processType == '经';
        });
        break;
      case 2:
        filterData = filterData.filter((item) => {
          return item.processType == '督';
        });
        break;
      default:
        filterData = [...filterData];
    }

    switch (sort) {
      case 1:
        filterData.sort((a, b) => {
          return a.expiredTime - b.expiredTime;
        });
        break;
      case 2:
        filterData.sort((a, b) => {
          return b.expiredTime - a.expiredTime;
        });
        break;
      default:
        filterData.sort((a, b) => {
          return a.createTime - b.createTime;
        });
    }

    this.showData = [];
    this.showData = [...filterData];
    this.showDataLoading = false;
    // console.log('待办展示数据--', this.showData);
  }

  filter(item, value) {
    if (item.businessKey.indexOf(value) > -1) {
      return true;
    }
    if (item.carLicense && item.carLicense.indexOf(value) > -1) {
      return true;
    }
    let content = item.content;
    let result = false;
    for (const key in content) {
      let keyValue = '' + content[key];
      result = keyValue.indexOf(value) > -1;
      if (result === true) {
        return result;
      }
    }
    return false;
  }

  showProcessClass(type) {
    let showType = 'handle';
    if (type == '经') {
      showType = 'handle';
    } else if (type == '督') {
      showType = 'supervise';
    }
    return showType;
  }

  searchKeywords(param) {
    let value = param.target.value;
    if (value) {
      this.showFilterToDoListData(value);
    } else {
      this.showToDoListData();
    }
  }

  searchReceiptKeywords(param) {
    let value = param.target.value;
    if (value) {
      this.popoverItem = this.showItemType.filter((item) => {
        return item.name.indexOf(value) > -1;
      });
    } else {
      this.checkShowItemType();
    }
  }

  clearReceiptValue() {
    this.searchReceiptValue = null;
    this.checkShowItemType();
  }


  checkShowItemType() {
    if (this.searchReceiptValue != null && this.searchReceiptValue != '') return;
    this.popoverItem = deepClone(this.showItemType);
  }

  selectData(item) {
    if (item.hasOwnProperty('tags')) {
      item['OAInterface'] = false;
      item['id'] = item['businessKey'];
      if (item.hasOwnProperty('formId')) {
        this.formService.navigateToForm(item);
        this.buttonService.getMenuLog('/' + item.formId, 'todo');
      } else {
        this.msg.error('该待办未配置具体页面！');
      }
    } else {
      this.formService.navigateToForm(item);
      this.buttonService.getMenuLog('/' + item.formId, 'todo');
    }
  }

  selectShowALlItemType(check) {
    // let check = boolean;
    this.indeterminate = false;
    this.showItemType.forEach((type) => {
      type.checked = check;
    });

    this.checkShowItemType();

    this.changeSort();
  }

  changShowItemType(item) {

    this.showItemType.forEach((show) => {
      if (show.name == item.name) {
        show.checked = item.checked;
      }
    });

    if (this.showItemType.every(item => !item.checked)) {
      this.showAllItemType = false;
      this.indeterminate = false;
    } else if (this.showItemType.every(item => item.checked)) {
      this.showAllItemType = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }

    this.changeSort();
  }

  private audio() {
    //if (!this.isPermissionGranted()) return;
    let audio = new Audio();
    audio.src = 'assets/audio/message.mp3';
    audio.load();
    audio.play();
  }

  checkUserAccount() {
    const userInfo = this.userService.getUserInfoObj();
    return userInfo.userAccount;
  }

  checkDeptId() {
    let userAccount = this.checkUserAccount();
    this.userInfo = userAccount;
    this.deptId = userAccount.post.dept ? userAccount.post.dept.id : null;
  }

  // 门店数据
  getStoreData() {
    let api = 'fn.workDeskTask.deptSalesReportDetail';
    let setData = { 'DEPT': this.deptId };
    this.apiService.post(api, setData).subscribe((data) => {
      // console.log('门店数据--', data);
      if (data) {
        this.storeData = data;
      }
    });
  }

  // 个人数据
  getPersonalData() {
    let api = 'fn.workDeskTask.personSalesRpeortDetail';
    let setData = { 'DEPT_ID': this.deptId };
    this.apiService.post(api, setData).subscribe((data) => {
      // console.log('个人数据--', data);
      if (data) {
        this.personalData = data;
      }
    });
  }

  // 智能助手
  getIntelligentAssistant() {
    let api = 'fn.smartHelperService.findSmartHelper';
    let setData = { 'DEPT_ID': this.deptId };
    this.intelligentLoading = true;
    this.apiService.post(api, setData).subscribe((data) => {
      // console.log('智能助手--', data);
      if (data) {
        this.intelligentData = data;
      }
      this.intelligentLoading = false;
    });
  }

  checkBoxCol(main, current) {
    let items = main.items;
    let len = current.data.length;
    let col = '100%';
    let check = false;
    let num = 0;
    switch (items.length) {
      case 1:
        col = '100%';
        break;
      case 2:
        items.forEach((item) => {
          if (item.data.length > 1) {
            check = true;
          }
        });
        if (check) {
          if (len == 1) {
            col = '25%';
          } else {
            col = '75%';
          }
        } else {
          col = '50%';
        }
        break;
      case 3:
        items.forEach((item) => {
          if (item.data.length > 2) {
            num += 1;
            check = true;
          }
        });
        if (check) {
          if (num < 3) {
            if (len < 3) {
              col = '25%';
            } else {
              col = '52%';
            }
          } else {
            col = '33%';
          }
        } else {
          col = '33%';
        }
        break;
      case 4:
        items.forEach((item) => {
          if (item.data.length == 1) {
            num += 1;
            check = true;
          }
        });
        if (check) {
          if (num == 1) {
            if (len == 1) {
              col = '12.5%';
            } else {
              col = '29%';
            }
          } else if (num == 2) {
            if (len == 1) {
              col = '12.5%';
            } else {
              col = '37.5%';
            }
          } else if (num == 3) {
            if (len == 1) {
              col = '12.5%';
            } else {
              col = '62.5%';
            }
          } else {
            col = '25%';
          }
        } else {
          col = '25%';
        }
        break;
    }
    return col;
  }

  checkBoxMainCol(main, current) {
    let items = main.data;
    let col = 12;
    switch (items.length) {
      case 1:
        col = 24;
        break;
      case 2:
        col = 12;
        break;
      case 3:
        col = 8;
        break;
      case 4:
        col = 12;
        break;
    }
    return col;
  }


  ngOnDestroy() {
    if (this.time) {
      clearInterval(this.time);
    }
    if (this.refreshFnWorkbench) {
      clearInterval(this.refreshFnWorkbench);
    }
    if (this.messagesSubscription) {
      this.messagesSubscription.unsubscribe();
    }
  }

}
